﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace slTestingStreaming
{
    public partial class myRichTextArea : UserControl
    {
        

        const int MaxRowLength = 20; //45;
        public myRichTextArea()
        {
            InitializeComponent();
        }

        #region UnformatedText


        public string UnformatedText
        {
            get { return (string)GetValue(UnformatedTextProperty); }
            set { SetValue(UnformatedTextProperty, value); }
        }

        public static readonly DependencyProperty UnformatedTextProperty =
            DependencyProperty.Register("UnformatedText", typeof(string), typeof(myRichTextArea), new PropertyMetadata(UnformatedTextPropertyChanged));




        private static void UnformatedTextPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            RichTextBox rta = ((myRichTextArea)obj).rta;
            Paragraph p = new Paragraph();
            p.Inlines.Add((string)args.NewValue);
            rta.Blocks.Add(p);
            rta.IsReadOnly = true;

        }
        

        #endregion

        #region Tweet


        public TweetGeo Tweet
        {
            get { return (TweetGeo)GetValue(TweetProperty); }
            set { SetValue(TweetProperty, value); }
        }

        public static readonly DependencyProperty TweetProperty =
            DependencyProperty.Register("Tweet", typeof(TweetGeo), typeof(myRichTextArea), new PropertyMetadata(TweetPropertyChanged));

        private static void TweetPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            try
            {
                TweetGeo tweet = (TweetGeo)args.NewValue;
                RichTextBox rta = ((myRichTextArea)obj).rta;
                Grid grdContainer = ((myRichTextArea)obj).grdDynamicControls;
                Paragraph p = new Paragraph();
                

                int currentLetterTotalCount = 0;

                //======================================================================
                //HACK TO CLEAR RTA'S WHICH SEEM TO NOT BE DISPOSING OF PREVIOUS CONTENT
                //======================================================================
                rta.Blocks.Clear();
                rta.Blocks.Add(p);
                grdContainer.Children.Clear();


                #region Time
                //p.Inlines.Add(tweet.CreatedAtString + " ");
                #endregion

                //=================================================================================================
                //HACK TO REMOVE INLINE IMAGES - CAUSES WSOD (there is a second in the "Text Stream" piece of code)
                //=================================================================================================
                
   
                #region Text Stream

                string text = tweet.text;

                text = text.Replace("\n", " ");
                
                if (!string.IsNullOrEmpty(text))
                {
                    string[] words = text.Split(' ');

                    foreach (string word in words)
                    {
                        

                        if (StringHelper.ContainsHyperlink(word))
                        {
                            #region HYPERLINK SEQUENCE
                            MatchCollection matches = StringHelper.GetHyperlinks(word);
                            int pos = 0;
                            foreach (Match m in matches)
                            {
                                try
                                {
                                    if (pos < m.Index)
                                    {
                                        p.Inlines.Add(word.Substring(pos, m.Index - pos));
                                    }



                                    string wordURL = m.Value;
                                    if (!wordURL.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) && !wordURL.StartsWith("https://", StringComparison.CurrentCultureIgnoreCase) && !wordURL.StartsWith("ftp://", StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        wordURL = "http://" + wordURL;
                                    }

                                    //==========================================
                                    //HACK TO REMOVE INLINE IMAGES - CAUSES WSOD
                                    //==========================================
                                    
                                    #region Hyperlink
                                    InlineUIContainer iuc = new InlineUIContainer();
                                    string hlDisplayText = m.Value; if (hlDisplayText.Length > MaxRowLength) hlDisplayText = hlDisplayText.Substring(0, MaxRowLength - 3) + "...";
                                    currentLetterTotalCount += hlDisplayText.Length;
                                    InlineHyperlink b = new InlineHyperlink();
                                    b.DynamicControlsContainer = grdContainer;
                                    //b.ShowImageUri += new InlineHyperlink.ShowImageUriHandler(b_ShowImageUri);
                                    //b.ShowHtmlUri += new InlineHyperlink.ShowHtmlUriHandler(b_ShowHtmlUri);
                                    b.DisplayLink = hlDisplayText;
                                    b.LinkUri = new Uri(wordURL);
                                    b.Tag = new Uri(wordURL);
                                    //b.Foreground = new SolidColorBrush(Color.FromArgb(255, 68, 121, 167));
                                    b.FontWeight = FontWeights.Normal;
                                    b.Cursor = Cursors.Hand;
                                    if (currentLetterTotalCount > MaxRowLength)
                                    {
                                        p.Inlines.Add("\n");
                                        iuc.Child = b;
                                        p.Inlines.Add(iuc);
                                        currentLetterTotalCount = hlDisplayText.Length;
                                    }
                                    else
                                    {
                                        iuc.Child = b;
                                        p.Inlines.Add(iuc);
                                        p.Inlines.Add(" ");
                                    }
                                    
                                    
                                    #endregion

                                }
                                catch
                                {
                                    p.Inlines.Add(m.Value);
                                }

                                pos = m.Index + m.Length;
                            }

                            // Add the remaining text to this textblock
                            if (pos < word.Length)
                            {
                                p.Inlines.Add(word.Substring(pos));
                            }

                            #endregion
                        }
                        else if (
                            (
                                word.StartsWith("@")
                                ||
                                word.StartsWith(".@") // 'cool kid' trying to bypass broken @replies
                                ||
                                word.StartsWith("-@") // ... 
                                ||
                                word.StartsWith("r@") // ... 
                                ||
                                word.StartsWith("rt@") // semi broken RT?
                            )
                            &&
                            word != "@")
                        {
                            #region @ SEQUENCE
                            string tmpword = word;
                            if (!word.StartsWith("@"))
                            {
                                p.Inlines.Add(word.Substring(0, word.IndexOf("@")));
                                tmpword = word.Substring(word.IndexOf("@"));
                            }

                            InlineUIContainer iuc = new InlineUIContainer();
                            string hlDisplayText = tmpword;
                            currentLetterTotalCount += hlDisplayText.Length;
                            InlineHyperlink b = new InlineHyperlink();
                            b.DynamicControlsContainer = grdContainer;
                            //b.ShowImageUri += new InlineHyperlink.ShowImageUriHandler(b_ShowImageUri);
                            //b.ShowHtmlUri += new InlineHyperlink.ShowHtmlUriHandler(b_ShowHtmlUri);
                            b.DisplayLink = hlDisplayText;
                            b.LinkUri = new Uri("http://twitter.com/" + tmpword.GetTwit());
                            //b.Foreground = new SolidColorBrush(Color.FromArgb(255, 68, 121, 167));
                            b.FontWeight = FontWeights.Normal;
                            b.Cursor = Cursors.Hand;

                            b.VerticalAlignment = VerticalAlignment.Bottom;
                            if (currentLetterTotalCount > MaxRowLength)
                            {
                                iuc.Child = b;
                                p.Inlines.Add("\n"); p.Inlines.Add(iuc);
                                currentLetterTotalCount = hlDisplayText.Length;
                            }
                            else
                            {
                                iuc.Child = b;
                                p.Inlines.Add(iuc);
                            }
                            #endregion
                        }
                        else if (word.StartsWith("#") && word != "#")
                        {
                            #region # SEQUENCE
                            string tmpword = word;
                            if (!word.StartsWith("#"))
                            {
                                p.Inlines.Add(word.Substring(0, word.IndexOf("#")));
                                tmpword = word.Substring(word.IndexOf("#"));
                            }

                            InlineUIContainer iuc = new InlineUIContainer();
                            string hlDisplayText = tmpword;
                            currentLetterTotalCount += hlDisplayText.Length;
                            InlineHyperlink b = new InlineHyperlink();

                            b.DisplayLink = hlDisplayText;
                            b.LinkUri = new Uri("http://twitter.com/" + tmpword.GetTwit());
                            b.DynamicControlsContainer = grdContainer;
                            //b.ShowImageUri += new InlineHyperlink.ShowImageUriHandler(b_ShowImageUri);
                            //b.ShowHtmlUri += new InlineHyperlink.ShowHtmlUriHandler(b_ShowHtmlUri);
                            //b.Foreground = new SolidColorBrush(Color.FromArgb(255, 68, 121, 167));
                            b.FontWeight = FontWeights.Normal;
                            b.Cursor = Cursors.Hand;

                            b.VerticalAlignment = VerticalAlignment.Bottom;
                            if (currentLetterTotalCount > MaxRowLength)
                            {
                                iuc.Child = b;
                                p.Inlines.Add("\n"); p.Inlines.Add(iuc);
                                currentLetterTotalCount = hlDisplayText.Length;
                            }
                            else
                            {
                                iuc.Child = b;
                                p.Inlines.Add(iuc);
                            }
                            #endregion
                        }
                        else
                        {
                            currentLetterTotalCount += word.Length;
                            p.Inlines.Add(word);
                        }

                        //Remember to add the spaces back between words, otherwise its not pretty.
                        if (currentLetterTotalCount > MaxRowLength) { p.Inlines.Add("\n"); currentLetterTotalCount = 0; }
                        else p.Inlines.Add(" ");
                        
                    }

                }

                #endregion

                #region HiddenWidth

                //string hlMissing = "\n " + PaddCharacter("X");
                //InlineUIContainer iuc = new InlineUIContainer();
                //TextBlock tb2 = new TextBlock();
                //tb2.Text = hlMissing;
                //tb2.Foreground = new SolidColorBrush(Colors.White);
                //iuc.Child = tb2;
                //p.Inlines.Add(hlMissing);
            
                #endregion

                //rta.Blocks.Add(p);
                rta.IsReadOnly = true;
            }
            catch (Exception ex) { }

            
        }



        static void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            //HyperlinkButton b = e.OriginalSource as HyperlinkButton;
            //Models.ModelLocator.Instance.Twitter.HyperlinkClicked((Uri)((Button)sender).Tag);
        }

        private static string PaddCharacter(string c)
        {
            string r = "";
            for (int i = 0; i < MaxRowLength+10; i++)
            {
                r += c;
            }
            return r;
        }
        #endregion

    }



}
